package server;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

/*
* 封装Response对象，需要依赖于OutputStream
* 该对象需要提供核心方法，输出html
* */
public class Response {
    private OutputStream outputStream;

    public Response() {
    }

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    //使用输出流输出指定字符串
    public void outPut(String content) throws IOException {
        outputStream.write(content.getBytes());
    }

    /*
    * path url
    *
    *   / -----> classes 目录
    * */
    public void outPutHtml(String path) throws IOException {
        //获取静态资源文件的绝对路径
        String absoluteResourcePath =StaticResourceUtil.getAbsolutePath(path);

        //输入静态资源文件
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()){
            //输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream);
        }else{
            //输出404
            outPut(HttpProtocolUtil.getHttpHeader404());
        }
    }

    public void outPutHtml_v4(String webappsPath,String path) throws IOException {
        //获取静态资源文件的绝对路径
        //String absoluteResourcePath =StaticResourceUtil.getAbsolutePath(path);
        //String absoluteResourcePath ="E:\\idea_workspace_02\\Minicat_V4\\src\\main\\java\\webapps"+absPath;

        String absPath = path.replaceAll("/", "\\\\");
        String absoluteResourcePath =webappsPath+absPath;

        //输入静态资源文件
        File file = new File(absoluteResourcePath);
        if (file.exists() && file.isFile()){
            //输出静态资源
            StaticResourceUtil.outputStaticResource(new FileInputStream(file),outputStream);
        }else{
            //输出404
            outPut(HttpProtocolUtil.getHttpHeader404());
        }
    }
}
